﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Security.Principal;
using EIIS.FrameWork.Attributes;
using EIIS.Infrastructure.Model.System.Authority;
using System.Configuration;

namespace EIIS.Presentation.Controllers.CommonSupport.Filter
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            string strDBKey = ConfigurationManager.AppSettings["DBKey"];
            if (string.IsNullOrEmpty(strDBKey))
            {
                filterContext.Result = new ContentResult { Content = "JSHelper.ShowError('抱歉,您的系统已过期！')" };
                return;
            }
            else
            {
                try
                {
                    strDBKey = EIIS.Common.DEncrypt.DESEncrypt.Decrypt(strDBKey, "px!=630");
                    DateTime dbKey = DateTime.Parse(strDBKey);
                    DateTime now = DateTime.Now;
                    TimeSpan ts = dbKey - now;
                    if (ts.Days < 0)
                    {
                        filterContext.Result = new ContentResult { Content = "JSHelper.ShowError('抱歉,您的系统已过期！')" };
                        return;
                    }
                }
                catch
                {
                    filterContext.Result = new ContentResult { Content = "JSHelper.ShowError('抱歉,您的系统已过期！')" };
                    return;
                }
            }

            var path = filterContext.HttpContext.Request.Path.ToLower();
            if (path == ("/Home/Login").ToLower() 
                || path == ("/Home/DoLogin").ToLower()
                || path == ("/Home/Logout").ToLower())//忽略对Login登录页的权限判定
                return;

            object[] attrs_Viewpage = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true);

            var isViewPage = (attrs_Viewpage.LongCount() == 1);

            string strActionType = "";
            if (!AuthorizeCore(filterContext, ref strActionType))
            {
                if (strActionType == "page" || isViewPage) 
                    filterContext.Result = new HttpUnauthorizedResult();//菜单页面跳转到登陆页
                else
                    filterContext.Result = new ContentResult { Content = "JSHelper.ShowError('抱歉,你不具有当前操作的权限！')" };//功能权限弹出提示框
            }


            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();

            base.OnActionExecuting(filterContext);
        }

        protected virtual bool AuthorizeCore(ActionExecutingContext filterContext,ref string strActionType)
        {
            if (filterContext.HttpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            CurrentUser user = new CurrentUser();//获取当前用户信息    
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated || user.UserInfo == null)
            {
                var path = filterContext.HttpContext.Request.Path.ToLower();
                if (path == "/" 
                    || path == ("/Home/Index").ToLower()
                    || path == ("/Home/Default").ToLower() 
                    || path == ("/HospUser/ModifyPWD").ToLower()
                    )
                {
                    strActionType = "page";
                }
                return false;//判定用户是否登录
            }
            else
            {                
                string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
                string actionName = filterContext.RouteData.Values["action"].ToString().ToLower();
                object[] attrs_Viewpage = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true);
                if (attrs_Viewpage.LongCount() > 0)
                {
                    strActionType = "page";
                    if ((attrs_Viewpage[0] as ViewPageAttribute).IsMenu)
                    {
                        if (user.MenuPermission != null)
                        {
                            int iCount = user.MenuPermission.Count<MenuNode>(m => !string.IsNullOrEmpty(m.ControllerName) && m.ControllerName.ToLower() == controllerName && !string.IsNullOrEmpty(m.ActionName) && m.ActionName.ToLower() == actionName);
                            return iCount > 0;
                        }
                        else return false;
                    }
                }
                object[] attrs_Button = filterContext.ActionDescriptor.GetCustomAttributes(typeof(FunctionAttribute), true);
                if (attrs_Button.LongCount() > 0)
                {
                    strActionType = "button";
                    if (user.ActionPermission != null)
                    {
                        int iCount = user.ActionPermission.Count(a => !string.IsNullOrEmpty(a.ControllerName) && a.ControllerName.ToLower() == controllerName && !string.IsNullOrEmpty(a.ActionName) && a.ActionName.ToLower() == actionName);
                        return iCount > 0;
                    }
                    else return false;
                }
            }
            return true;
        }
    }
}
